var MultiSteps = {}; // Exposes the forward() method publicly so finch tests can grab it

$(function() {

  var currentStepIdx = 0;
  var stepClasses = ["step_one", "step_two", "step_three"];
  var animating = false;
  var resizing = false;
  var resizeTimer = null;
  var subscriptionRequestPending = false;
  var placesRequestPending = false;

  setDivision($("#subscription_division_id").val());
  $("#subscription_division_id").bind("change", function() {
    setDivision($(this).val());
  });

  $(".step_one .button.continue").click(function(e) {
    e.preventDefault();
    Groupon.Subscription.Tracker.get().trackClickDivisionSuccessFromMultiStep();
    forward();
  });

  $(".step_two .button.continue").bind("click", function(e) {
    if (!$("#new_subscription").valid()) { e.preventDefault(); return false; }
    Groupon.Subscription.Tracker.get().trackSubscriptionSubmitFromMultiStep();
    return true;
  });

  function submitSubscription() {
    if (subscriptionRequestPending) { return false; }
    if ($("#new_subscription").valid()) { subscriptionRequestPending = true; }

    var formData = {};
    $("#new_subscription :input").serializeArray().each(function(item) { formData[item.name] = item.value; });
    var url = $("#new_subscription").attr("action");
    Groupon.Subscription.Tracker.get().trackSubscriptionPreAjaxFromMultiStep();
    $.ajax({
      type: "POST",
      url: url,
      data: formData,
      success: function() {
        Groupon.Subscription.Tracker.get().trackPlacesSuccessFromMultiStep();
      },
      error: function() {
        Groupon.Subscription.Tracker.get().trackPlacesFailFromMultiStep();
        goToDivisionPage();
        subscriptionRequestPending = false;
      },
      complete: function(xhr,status){
        switch(status){
        case "success":
          Groupon.Subscription.Tracker.get().trackPlacesAjaxCompleteSuccess();
          setSubscriptionCookies(formData["subscription[email_address]"]);
          MultiSteps.forward = function() {
            Groupon.Subscription.Tracker.get().trackPlacesSuccessMultiStepAdvance();
            $(".step_three").fadeIn(200, function() { forward(); });
          };
          goToAllDealsPage();
          break;
        case "error":
          Groupon.Subscription.Tracker.get().trackPlacesAjaxCompleteError();
          break;
        case "abort":
          Groupon.Subscription.Tracker.get().trackPlacesAjaxCompleteAbort();
          break;
        case "notmodified":
          Groupon.Subscription.Tracker.get().trackPlacesAjaxCompleteNotModified();
          break;
        case "timeout":
          Groupon.Subscription.Tracker.get().trackPlacesAjaxCompleteTimeout();
          break;
        case "parsererror":
          Groupon.Subscription.Tracker.get().trackPlacesAjaxCompleteParseError();
          break;
        default:
          
          break;
        }
      }
    });
  }

  $(".gender_box").bind("click", function() {
    $(".selection", this).children("input").attr("checked", true);
  });

  $("#submit_gender").bind("click", function(e) {
    if (placesRequestPending) { e.preventDefault(); return false; }
    if (!$("#accept_terms").is(":checked")) {
      highlightTOC();
    } else {
      submitGender();
      goToAllDealsPage();
    }
  });

  $("#submit_places").bind("click", function(e) {
    if (placesRequestPending) { e.preventDefault(); return false; }
    submitPlaces();
  });

  $("input.places_entry").bind("keyup", function(e) {
    if (placesRequestPending) { e.preventDefault(); return false; }
    if (e.keyCode == 13) { submitPlaces(); }
  });

  // Tracking for zip/gender subscription modal
  $("#zip_gender #sign_up_button").bind("click", function() {
    var submitted_zipcode = $("#zip_gender #subscription_zipcode").val();
    var submitted_gender = $("#zip_gender #subscription_gender").val();

    if (!isNaN(parseInt(submitted_zipcode))) {
      Groupon.Subscription.Tracker.get().trackZipFromZipGenderSubscriptionModal();
    }
    if (submitted_gender == 'male' || submitted_gender == 'female') {
      Groupon.Subscription.Tracker.get().trackGenderFromZipGenderSubscriptionModal();
    }
  });

  // pre-pop for zip/gender (TODO: better check for visable zip/gender modal)
  if ($('#subscription_zipcode').length && ($('#subscription_zipcode').val() == '' || $('#subscription_zipcode').val().match("ex. "))) {
    theZip = null;
    if (Groupon.currentUser.places) {
      homes = _(Groupon.currentUser.places).filter(function(p) { return p.name === "home"; });
      if (homes) {
        theZip = pullZip(homes.last().location_string);
      }
    }
    if (!theZip && Cookie.get('search_loc')) {
      if (JSON.parse(Cookie.get('search_loc'))) {
        theZip = pullZip(JSON.parse(Cookie.get('search_loc')).full_address);
      }
    }
    if (theZip) {
      $('#subscription_zipcode').val(theZip);
      $('#subscription_zipcode').removeClass('prompting');
    }
  }

  function pullZip(aString) {
    zipCheck = RegExp(/\d{5}(-\d{4})?/); //just US for now
    aZip = zipCheck.exec(aString);
    if (aZip) {
      return aZip.first();
    } else {
      return null;
    }
  }

  function highlightTOC() {
    $(".toc").addClass("error");
    return false;
  }

  $("#accept_terms").bind("change", function() {
    if ($(this).is(":checked")) {$(".toc").removeClass("error");}
  });

  function determineGender() {
    var gender = "none";
    if ($("#gender_male").is(":checked")) {gender="male";}
    if ($("#gender_female").is(":checked")) {gender="female";}
    return gender;
  }

  function submitGender() {
    Groupon.Subscription.Tracker.get().trackGenderFromPlacesSubscriptionModal();
    placesRequestPending = true;
    var genderString = determineGender();
    if (genderString == "male" || genderString == "female") {
      $.ajax({
        url: "user_demographics/update_gender",
        type: "POST",
        async: false,
        data: { gender: genderString, _method: 'PUT' },
        dataType: "json",
        success: function() {
          placesRequestPending = false;
        }
      });
    }
  }

  function submitPlaces() {
    Groupon.Subscription.Tracker.get().trackPlacesFromPlacesSubNonModal();
    placesRequestPending = true;
    _.each(["home", "work"], function(name) {
      var locationString = $("#" + name + "_address").val();
      if (locationString.length > 0) {
        $.ajax({
          url: "/places",
          type: "POST",
          async: false,
          data: { name: name, location_string: $("#" + name + "_address").val() },
          dataType: "json",
          success: function() {
            $("#" + name + "_address").removeClass("error");
            $("label.error." + name).hide();
            placesRequestPending = false;
          },
          error: function(xhr) {
            if (!xhr.responseText.match(/profile_id/)) { // Avoids duplicate errors from stopping the process
              $("#" + name + "_address").addClass("error");
              $("label.error." + name).show();
            }
            placesRequestPending = false;
          }
        });
      }
    });
    if ($(".step_three input.error").length == 0) {
      goToAllDealsPage();
    }
  }

  $("#skipPlaces").bind("click", function(e) {
    if (placesRequestPending) {
      e.preventDefault();
      return false;
    }
    goToDivisionPage();
  });

  $("#home_address").bind("keyup", function() {
    var len = $("#home_address").val().length;
    if (len > 0) {
      $(".step_three .places_step_two").slideDown();
      $(".step_three .continue.first_btn").slideUp(200, function() {
        $(".step_three .continue.second_btn").slideDown(200);
      });
    } else {
      $(".step_three .places_step_two").slideUp();
      $(".step_three .continue.second_btn").slideUp(200, function() {
        $(".step_three .continue.first_btn").slideDown(200);
      });
    }
  });

  $(".button_container .facebook_login").click(function(e) {
    e.preventDefault();
    $(".step_two")
      .find("fieldset").hide().end()
      .find(".button_container").hide().end()
      .find(".fb_registration_h1").show().end()
      .find("iframe").show();
    forward();
  });

  $("#feature_toggle a").click(function(e) {
    e.preventDefault();
    Effect.toggle("featured", "slide", { duration: 0.25 });
  });

  $(window).resize(function() {
    resizing = true;
    if (resizeTimer !== null) {
      window.clearTimeout(resizeTimer);
    }
    resizeTimer = window.setTimeout(pageRedraw, 200);
  });

  animateSteps(false);

  function forward() {
    if (currentStepIdx == 1 && !$("#new_subscription").valid()) { return; }
    if (!animating) {
      animating = true;
      currentStepIdx++;
      animateSteps(1000);

      // in case someone hit enter on one of the first steps
      if (currentStepIdx == (stepClasses.length - 1)) {
        $("#subscription_submit").removeClass("disabled");
      }
    }
  }

  function getSteps() {
    var oldStep = (currentStepIdx == (stepClasses.length - 1)) ? stepClasses[0] : null;
    var currentStep = stepClasses[currentStepIdx];
    var prevStep = (currentStepIdx > 0) ? stepClasses[currentStepIdx - 1] : null;
    var nextStep = (currentStepIdx < (stepClasses.length - 1)) ? stepClasses[currentStepIdx + 1] : null;
    var superStep = (currentStepIdx == 0) ? stepClasses[stepClasses.length - 1] : null;
    return { old: oldStep, curr: currentStep, prev: prevStep, next: nextStep, supr: superStep };
  }

  function pageRedraw() {
    resizing = false;
    animateSteps(300);
  }

  function animateSteps(speed) {
    var pos = calculatePositions();
    var steps = getSteps();
    var animCallback = function() { };
    var animSpeed = speed;

    if (!speed) {
      animSpeed = 1;
      animCallback = function() {
        animating = false;
      };
    } else {
      animCallback = function() {
        $("." + steps.curr + " input:first").focus();
      };
    }

    $("." + steps.old).animate({ left: pos.offLeft + "px", opacity: 0.3 }, animSpeed);
    $("." + steps.prev).animate({ left: pos.left + "px", opacity: 0.3 }, animSpeed);
    $("." + steps.curr).animate({ left: pos.center + "px", opacity: 1 }, { duration: animSpeed, complete: animCallback });
    $("." + steps.next).animate({ left: pos.right + "px", opacity: 0.3 }, animSpeed);
    $("." + steps.supr).animate({ left: pos.offRight + "px", opacity: 0.3 }, animSpeed);

    if (speed) { animating = false; }
  }

  function clearAnimateFlag() {
    animating = false;
  }

  function calculatePositions() {
    var offset = 20;
    var step_width = $(".form_step").width() / 2;
    var window_width = $(window).width();

    var offLeft = -3 * step_width;
    var leftPos = offset - step_width;
    var centerPos = window_width / 2;
    var rightPos = window_width - offset + step_width;
    var offRight = rightPos + (3 * step_width);
    return { offLeft: offLeft, left: leftPos, center: centerPos, right: rightPos, offRight: offRight };
  }

  function setSubscriptionCookies(emailAddress) {
    Cookie.set("scid", $.sha256(emailAddress), 60*60*24*365*10);
    Cookie.set("division", Groupon.currentDivision, 60*60*24*30);
    Cookie.set("subscriber_email", emailAddress, 60*60*24*365*10);
    Cookie.set("visited", true, 60*60*24*365*10);
    if (Groupon.currentArea) {
      Cookie.set('area', Groupon.currentArea, 60*60*24*30);
    }
  }

  function setDivision(division_string) {
    //Avoid strange jasmine test failure
    if (typeof division_string == 'string') {
      var division_array = division_string.split(':');
      Groupon.currentDivision = division_array[0];
      Groupon.currentArea = division_array.length > 1 ? division_array[1] : undefined;
    }
  }

  function getFormParam() {
    var firstParam = '&' + ($('#new_subscription').attr('action').split('?')[1] || '');
    if (firstParam == '&') {
      firstParam = '';
    }
    return firstParam;
  }

  MultiSteps.getFormParam = getFormParam;

  function goToAllDealsPage(){
    window.location = '/' + Groupon.currentDivision + '/all?post_subscribe=true' + getFormParam();
  }

  function goToDivisionPage(){
    new_location = '/' + Groupon.currentDivision + '/';
    new_location += Groupon.currentArea ? 'area/'+Groupon.currentArea+'/' : '';
    window.location = new_location + '?post_subscribe=true' + getFormParam();
  }
});
